package org.xiangxji.snippets.junit;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.lang.reflect.Type;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.lang.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.xiangxji.snippets.db.DBConnectUtils;
import org.xiangxji.snippets.file.FileUtil;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


public class MainTest {
	public static int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 }; 
	
	public static void ShellSort(int Index) {
		int i, j, k; // 循环计数变量
		int Temp; // 暂存变量
		boolean Change; // 数据是否改变
		int DataLength; // 分割集合的间隔长度
		int Pointer; // 进行处理的位置
		DataLength = (int) Index / 2; // 初始集合间隔长度
		while (DataLength != 0) // 数列仍可进行分割
		{
			// 对各个集合进行处理
			for (j = DataLength; j<Index; j++) {
				Change = false;
				Temp = a[j]; // 暂存Data[j]的值,待交换值时用
				Pointer = j - DataLength; // 计算进行处理的位置
				// 进行集合内数值的比较与交换值
				while (Temp < a[Pointer] && Pointer >= 0 && Pointer <= Index) {
					a[Pointer + DataLength] = a[Pointer];
					// 计算下一个欲进行处理的位置
					Pointer = Pointer - DataLength;
					Change = true;
					if (Pointer < 0 || Pointer > Index)
						break;
				}
				// 与最后的数值交换
				a[Pointer + DataLength] = Temp;
				if (Change) {
					// 打印目前排序结果
					System.out.print("排序中: ");
					for (k = 0; k < Index; k++)
						System.out.printf("%3s ", a[k]);
					System.out.println("");
				}
			}
			DataLength = DataLength / 2; // 计算下次分割的间隔长度
		}
	}
	
	@Test
	public void testS() {
		List<Integer> s = new ArrayList<Integer>();
		s.add(5);
		s.add(8);
		s.add(1);
		s.add(3);
		s.add(9);
		s.add(6);
		s.add(7);
		for(int i : fast(s)){
			System.out.println(i);
		}
	}
	public void div(List<Integer> a,List<Integer> b,List<Integer> c,int m) {
		int tmp = a.get(m); 
		b.clear();
		c.clear();
		for(int i=0;i<a.size();i++) {
			if(a.get(i)<=tmp){ 
				b.add(a.get(i));
			} else {
				c.add(a.get(i));
			}
		}
		if(b.size()==0 || c.size()==0) {
			if(a.size()>=m+2) {	
				div(a,b,c,m+1);
			}else if(m-1>=0) {
				div(a,b,c,m-1);
			}
		}
	}
	public List<Integer> fast(List<Integer> a){
		int m = (a.size()-1)/2;
		List<Integer> r = new ArrayList<Integer>();
		if(a.size()==1) {
			r = a;
		}else if(a.size()==2) {
			if(a.get(0)<=a.get(1)) { 
				r = a;
			}else{
				r.add(0, a.get(1));
				r.add(1, a.get(0)); 
			}
		} else if(m>=1) {
			List<Integer> b = new ArrayList<Integer>();
			List<Integer> c = new ArrayList<Integer>();
			
			div(a,b,c,m);
			
			List<Integer> ret = fast(b);
			if(ret.size()>0) {
				for(int i = 0;i<ret.size();i++) {
					r.add(ret.get(i));
				}
			}
			List<Integer> ret1 = fast(c);
			if(ret1.size()>0) {
				for(int i = 0;i<ret1.size();i++) {
					r.add(ret1.get(i));
				}
			}
		}
		return r;
	}
	
	int hash(int h) {
        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }
	@Test
	public void testHashCode() {
		String x = "xiangxji";
		System.out.println(Integer.toBinaryString(x.hashCode()));
		System.out.println(Integer.toBinaryString(hash(x.hashCode())));
	}
	@Test
	public void testShort() {
		char c1 = 0;
		for(int i=0;i<70000;i++) {
			System.out.println(c1++);
		}
	}
	@Test
	public void testStringBuffer() {
		StringBuffer sb = new StringBuffer();
		String i = null;
		app(sb, i);
		System.out.println(sb.toString()); 
	}
	public void app(StringBuffer sb, String i) {
		sb.append("hello=").append(i);
	}
	@Test
	public void testOutPutPower() {
		for(int i = 15;i<17;i++) {
			long a = (long) Math.pow(2, i);
			System.out.println("private static final long TWO_SQUAL_"+i+" = "+a+"L;"); 
		}
	}
	
	@Test
	public void testBitComp() {
		long a = 536870912L;
//		long a = 805306368L;
		long b = (long) Math.pow(2, 30);
//		if((a&b)==b) {
//			System.out.println("true"); 
//		}
		long c = a|b; 
		System.out.println(Long.toBinaryString(c)); 
	}
	
	@Test
	public void testMemoryPool() {
		List<MemoryPool> res = getMemoryPools();
		for(MemoryPool m : res) {
			System.out.println("+--------------------------+"); 
			System.out.println("Name: " + m.getName());
			System.out.println("Type: " + m.getType());
			System.out.println(m.getInit()+" Byte");
			System.out.println(m.getMax()+" Byte");
			System.out.println(m.getUsed()+" Byte");
			System.out.println("Score: " + m.getUsageScore());
			System.out.println("+--------------------------+"); 
		}
	}
	
	public List<MemoryPool> getMemoryPools(){
		List<MemoryPool> memoryPools = new LinkedList<MemoryPool>();
		
		List<MemoryPoolMXBean> mPoolsList = ManagementFactory.getMemoryPoolMXBeans();
		if(mPoolsList == null){
			System.out.println("get memory pools error");
			return null;
		}
		//totals
		long totalInit = 0;
		long totalMax = 0;
		long totalUsed = 0;
		long totalCommitted = 0;
		
		for(MemoryPoolMXBean memoryPool : mPoolsList){
			MemoryPool mp = new MemoryPool();
			mp.setName(memoryPool.getName());
			mp.setType(memoryPool.getType().name());
			
			MemoryUsage mu = memoryPool.getUsage();
			if(mu != null){
				mp.setMax(mu.getMax());
				mp.setUsed(mu.getUsed());
				mp.setInit(mu.getInit());
				mp.setCommitted(mu.getCommitted());
			}else{
				System.out.println("Oops,Jvm problem?" + memoryPool.getName() + "\"Usage\" attribute is null");
			}
			totalInit += mp.getInit();
			totalMax += mp.getMax();
			totalUsed += mp.getUsed();
			totalCommitted += mp.getCommitted();
			memoryPools.add(mp);
		}
		if(!memoryPools.isEmpty()){
			MemoryPool pool = new MemoryPool();
			pool.setName("Total");
			pool.setType("TOTAL");
			pool.setInit(totalInit);
			pool.setUsed(totalUsed);
			pool.setMax(totalMax);
			pool.setCommitted(totalCommitted);
			memoryPools.add(pool);
		}
		return memoryPools;
	}
	
	@Test
	public void testUtilRandom() {
		Random rand1 = new Random();
		Random rand2 = new Random(20);
		
		System.out.println(rand1.nextInt()); 
		System.out.println(rand2.nextInt());
	}
	
	
	public class AAA {}
	
	public class BBB {}
	
	public class CCC{}
	
	@SuppressWarnings({ "rawtypes", "unused" })
	@Test
	public void testClassLoader() {
		
		try {
			ClassLoader sysLoader = ClassLoader.getSystemClassLoader();
			
			Class aa=AAA.class;
			Class bb=Class.forName("org.xiangxji.snippets.junit.MainTest$BBB");
			Class cc=ClassLoader.getSystemClassLoader().loadClass("org.xiangxji.snippets.junit.MainTest$CCC");
//			
//			System.out.println(ClassLoader.getSystemClassLoader().getResource("org/xiangxji/snippets/junit/MainTest/CCC"));
//			
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Test
	public void testStringAndStringBuffer() {
		String a = "";
		StringBuffer b = new StringBuffer();
		
		long s = 0L;
		
		System.out.println((s=System.currentTimeMillis()));
		for(int i=0;i<6000;i++) {
			b.append("*");
		}
		b.toString();
		System.out.println(System.currentTimeMillis()-s);
		
		s = System.currentTimeMillis();
		
		for(int i=0;i<6000;i++) {
			a+="*";
		}
		System.out.println(System.currentTimeMillis()-s); 
	}
	
	@Test
	public void testExec() {
		Process p=null;
		
		try {
			
			p=Runtime.getRuntime().exec("notepad.exe "+"C:"+File.separator+"testMain.java");//启动记事本并且打开源文件。
			Thread.sleep(5000); //持续5秒
			p.destroy(); //关闭该进程
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block 
			e.printStackTrace();
		} 
		
	}
	
	
	//"TAOBAO-01F7027C.taobao.ali.com", "root", "root", "trade_download"
	@Test
	public void testTempFile() throws IOException { 
		String content = "hello,world\r\nis this a new line?\r\nyes\r\nno";
		File file = File.createTempFile("recv", ".xml");
		FileWriter fw = new FileWriter(file);
		fw.write(content);
		fw.flush();
		fw.close();
	}
	@Test
	public void testJson() {
		Gson gson = new Gson();
		String str = "{\"notify_vas\":{\"topic\":\"vas\",\"amounts\":\"3654767==20.0==2011-01-12 00:01:02==2011-01-12 00:01:02\",\"nick\":\"tbtestuser815\",\"memo\":\"3654767==2005078525\",\"status\":\"VasBillingSuccess\",\"user_id\":179823769,\"service_code\":\"SERV_DXFW\",\"modified\":\"2011-01-12 14:16:42\"}}";
		Type type = new TypeToken<HashMap<String, HashMap<String,String>>>(){}.getType();
		HashMap<String, HashMap<String,String>> fromJson = gson.fromJson(str, type);

		HashMap<String,String> content = fromJson.get("notify_vas");
		for (String key : content.keySet()) {
			String s = content.get(key);
			System.out.println(String.format("%s:%s", key, s));
		}
	}
	@Test
	public void testJJson() {
		Long a = 1L;
		Long b = new Long(1);
		System.out.println(a.equals(b)?"yes":"no");
	}
	
	@Test
	public void testSMS() {
		boolean ok1 = true;
		boolean ok2 = false;
		if(true) {
			Assert.assertTrue(ok1);
			ok2 = true;
		}
		Assert.assertTrue(ok2);
	}
	
	@Test
	public void testString() {
		System.out.println(StringUtils.isNotBlank("hello"));
		Long s = System.currentTimeMillis();
		funca();
		Long e = System.currentTimeMillis() - s;
		s = System.currentTimeMillis();
		funcb();
		System.out.println(e); 
		System.out.println(System.currentTimeMillis() - s); 
	}
	public void funca() {
		String a = "hello,how are you";
		for(int j=0;j<5000;j++) {
			System.out.println(StringUtils.isNotBlank(a)?a+"!":a);
		}
	}
	public void funcb() {
		String a = "hello,how are you";
		for(int i=0;i<5000;i++) {
			if(StringUtils.isNotBlank(a)) {
				System.out.println(a+"!");
			} else {
				System.out.println(a);
			}
		}
	}
	
	@Test
	public void testInteger() {
		int h = 100;
		System.out.println(h);
		Integer a = h;
		System.out.println(a);
		long b = a;
		System.out.println(b);
	}
	
	
	@Test
	public void getConnTest() throws IOException, SQLException {  
		Connection conn = DBConnectUtils.getConnection("jdbc:mysql://localhost:3306/trade_log", "root", "");
		System.out.println(conn.getCatalog()); 
	}
	
	@Test
	public void testArrat() {
		String a = "中华人民共和国，中央人民政府十六";
		String b = "abcdefghjiklmnop";
		System.out.println(b.length()+":"+a.length()); 
	}
	
	public void writeLog(String s) {
		String filename = "D:\\\\backup\\\\import.log";
		RandomAccessFile rf;
		try {
			rf = new RandomAccessFile(filename,"rw");//定义一个类RandomAccessFile的对象，并实例化
			rf.seek(rf.length());//将指针移动到文件末尾
			rf.writeBytes(s+"\n");
			rf.close();//关闭文件流
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	@SuppressWarnings("deprecation")
	public int getDayOfWeek(Date d) {
		return d.getDay();
	}
	@Test
	public void startRunImport() {
		Timer timer = new Timer();
//		long ts = System.currentTimeMillis()+4000000;
		timer.schedule(new ImportTask(), 1000);
	}
	
	static class ImportTask extends TimerTask {

		public void writeLog(String s) {
			String filename = "D:\\\\backup\\\\import.log";
			RandomAccessFile rf;
			try {
				rf = new RandomAccessFile(filename,"rw");//定义一个类RandomAccessFile的对象，并实例化
				rf.seek(rf.length());//将指针移动到文件末尾
				rf.writeBytes(s+"\n");
				rf.close();//关闭文件流
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
		@SuppressWarnings("deprecation")
		public void importToDB() throws IOException {
			Date createDay = new Date(110, 11, 12);
			
			Connection conn = DBConnectUtils.getConnection("jdbc:mysql://localhost:3306/trade_download_log", "root", "");
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 
//			Date today = new Date(System.currentTimeMillis()-86400000);
			String t = sdf.format(createDay);
			Statement stmt;
			int d = createDay.getDay();
			try {
				stmt = conn.createStatement();
				String sql = "delete from trade_download_report_"+d;
//				System.out.println(sql);
				stmt.execute(sql);
			} catch (SQLException e1) {
				writeLog("error delete ");
				System.out.println("error");
				return;
			}
			
			String[] resources = FileUtil.splitDataFile("d:\\\\backup\\\\20101212\\\\tradeDownloadLogFinal.log", 50);
			for(int i=0;i<resources.length;i++) {
				File file = new File(resources[i]);
				FileReader fr = new FileReader(file);
				BufferedReader br = new BufferedReader(fr);
				String temp=null;
				int j=0;
				try {
					stmt = conn.createStatement();
					while((temp=br.readLine())!=null) {
						String[] arr = temp.split(",");
						if(arr.length<11) {
							writeLog(temp);
							System.out.println("1");
						}else {
							Date createDate = new Date(Long.valueOf(arr[10]));
							String c = sdf.format(createDate);
							String sql = "insert into trade_download_report_"+d+
							" (api,appkey, seller_nick, seller_type,tid, type, payment, total_fee, tradefrom, status, created, dump_time)"+
								"values ('"+arr[0]+"','"+arr[1]+"','"+arr[2]+"','"+arr[3]+"',"+arr[4]+","+arr[5]+","+arr[6]+","+arr[7]+",'"+arr[8]+"',"+arr[9]+",'"+c+"','"+t+"')";

								//System.out.println(sql);
								stmt.addBatch(sql);
								j++;
								if(j%1000==0 && j!=0) {
									stmt.executeBatch();
									stmt.clearBatch();
									j=0;
								}
//								boolean result = stmt.execute(sql);
						}
					}
					if(j!=0) {
						stmt.executeBatch();
						stmt.clearBatch();
						j=0;
					}
					
					stmt.close();
				} catch (SQLException e) {
					writeLog(temp);
					System.out.println("3");
				}
				br.close();
				fr.close();
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					writeLog(resources[i]);
					continue;
				}
			}
		}
		@SuppressWarnings("deprecation")
		public void importToDB10() throws IOException {
			Date createDay = new Date(110, 11, 13);
			
			Connection conn = DBConnectUtils.getConnection("jdbc:mysql://localhost:3306/trade_download_log", "root", "");
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 
//			Date today = new Date(System.currentTimeMillis()-86400000);
			String t = sdf.format(createDay);
			Statement stmt;
			int d = createDay.getDay();
			try {
				stmt = conn.createStatement();
				String sql = "delete from trade_download_report_"+d;
//				System.out.println(sql);
				stmt.execute(sql);
			} catch (SQLException e1) {
				writeLog("error delete ");
				System.out.println("error");
				return;
			}
			
			String[] resources = FileUtil.splitDataFile("d:\\\\backup\\\\20101213\\\\tradeDownloadLogFinal.log", 50);
			for(int i=0;i<resources.length;i++) {
				File file = new File(resources[i]);
				FileReader fr = new FileReader(file);
				BufferedReader br = new BufferedReader(fr);
				String temp=null;
				int j=0;
				try {
					stmt = conn.createStatement();
					while((temp=br.readLine())!=null) {
						String[] arr = temp.split(",");
						if(arr.length<11) {
							writeLog(temp);
							System.out.println("1");
						}else {
							Date createDate = new Date(Long.valueOf(arr[10]));
							String c = sdf.format(createDate);
							String sql = "insert into trade_download_report_"+d+
							" (api,appkey, seller_nick, seller_type,tid, type, payment, total_fee, tradefrom, status, created, dump_time)"+
								"values ('"+arr[0]+"','"+arr[1]+"','"+arr[2]+"','"+arr[3]+"',"+arr[4]+","+arr[5]+","+arr[6]+","+arr[7]+",'"+arr[8]+"',"+arr[9]+",'"+c+"','"+t+"')";

								//System.out.println(sql);
								stmt.addBatch(sql);
								j++;
								if(j%1000==0 && j!=0) {
									stmt.executeBatch();
									stmt.clearBatch();
									j=0;
								}
//								boolean result = stmt.execute(sql);
						}
					}
					if(j!=0) {
						stmt.executeBatch();
						stmt.clearBatch();
						j=0;
					}
					
					stmt.close();
				} catch (SQLException e) {
					writeLog(temp);
					System.out.println("3");
				}
				br.close();
				fr.close();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					writeLog(resources[i]);
					continue;
				}
			}
		}
		
		@Override
		public void run() {
			try {
				importToDB();
				Thread.sleep(3000);
				importToDB10();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	@SuppressWarnings("deprecation")
	@Test
	public void importLogs09() throws IOException {
		int dth = 28;
		int tth = 7;
		Date createDay = new Date(110, 11, dth);
		
		Connection conn = DBConnectUtils.getConnection("jdbc:mysql://localhost:3306/trade_download_log", "root", "");
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 
		String t = sdf.format(createDay);
		Statement stmt;
		PreparedStatement pstmt;
		try {
			stmt = conn.createStatement();
			String sql = "delete from trade_download_report_"+tth;
			stmt.execute(sql);
		} catch (SQLException e1) {
			writeLog("error delete ");
			System.out.println("error");
			return;
		}
		
//		String[] resources = FileUtil.splitDataFile("d:\\\\backup\\\\201012"+dth+"\\\\tradeDownloadLogFinal.log", 100);
		String[] resources = new String[]{"d:\\\\backup\\\\201012"+dth+"\\\\tradeDownloadLogFinalsub0.log"};
		for(int i=0;i<resources.length;i++) {
			System.out.println(tth+"-"+resources[i]);
			File file = new File(resources[i]);
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			String temp=null;
			int j=0;
			try {
				pstmt = conn.prepareStatement("insert into trade_download_report_"+tth+
						" (api,appkey, seller_nick, seller_type,tid, type, payment, total_fee, tradefrom, status, created, dump_time)"+
						"values (?,?,?,?,?,?,?,?,?,?,?,?)");
				while((temp=br.readLine())!=null) {
					String[] arr = temp.split(",");
					if(arr.length<11) {
						writeLog(temp);
						System.out.println("1");
					}else {
						Date createDate = new Date(Long.valueOf(arr[10]));
						String c = sdf.format(createDate);
						pstmt.setString(1, arr[0]);
						pstmt.setString(2, arr[1]);
						pstmt.setString(3, arr[2]);
						pstmt.setString(4, arr[3]);
						pstmt.setLong(5, Long.parseLong(arr[4]));
						pstmt.setInt(6, Integer.parseInt(arr[5]));
						pstmt.setDouble(7, Double.parseDouble(arr[6]));
						pstmt.setDouble(8, Double.parseDouble(arr[7]));
						pstmt.setString(9, arr[8]);
						pstmt.setInt(10, Integer.parseInt(arr[9]));
						pstmt.setString(11, c);
						pstmt.setString(12, t);

						pstmt.addBatch();
						j++;
						if(j%1000==0 && j!=0) {
							pstmt.executeBatch();
							pstmt.clearBatch();
							j=0;
						}
					}
				}
				if(j!=0) {
					pstmt.executeBatch();
					pstmt.clearBatch();
					j=0;
				}
				pstmt.close();
			} catch (SQLException e) {
				writeLog(temp);
				System.out.println(e.getMessage()); 
				System.out.println("3");
			}
			br.close();
			fr.close();
			try {
				Thread.sleep(800);
			} catch (InterruptedException e) {
				writeLog(resources[i]);
				continue;
			}
		}
	}
}
